import { defineStore } from 'pinia';
import dayjs from 'dayjs';
import lodash , { isUndefined, isNull } from 'lodash';

import { 
  setUserMobileList,
  getUserMobileList,
  clearUserMobileList,
} from '@/utils/auth';

export interface UserMobile {
  uid: number,
  mobile: string,
  expired: number, 
}

export interface CommonState {
  userMobile: UserMobile[]
}

const useCommonStore = defineStore('common', {
  state: (): CommonState => ({
    userMobile: undefined,
  }),
  getters: {
    getUserMobileArray(state: CommonState){
       return state.userMobile
    }
  },
  actions: {
    addUserMobile(data: UserMobile){
      if(!isNull(this.userMobile) && !isUndefined(this.userMobile) && Array.isArray(this.userMobile)){
        const findItem = lodash.find(this.userMobile,(item)=> item?.uid === data?.uid);
        if(isUndefined(findItem)){ 
          let addList = [].concat(this.userMobile,[ data ])
          this.setUserMobileData({ userMobile: addList });
          setUserMobileList(addList);
        }
      } else {
        let addArray: UserMobile[] = []; addArray.push(data);
        this.setUserMobileData({ userMobile: addArray });
        setUserMobileList(addArray);
      }
    },
    clearExpiredUserMoble(){
      const currentTime = dayjs().valueOf();
      if(!isNull(this.userMobile) && !isUndefined(this.userMobile) && Array.isArray(this.userMobile)){
        lodash.remove(this.userMobile,(item: any )=> currentTime >= item?.expired);
        setUserMobileList(this.userMobile);
      }
    },
    setUserMobileData(partial: Partial<CommonState>) {
        this.$patch(partial);
    },
    getUserMobileByUid(uid: number){
      const currentTime = dayjs().valueOf();
      if(!isNull(this.userMobile) && !isUndefined(this.userMobile) && Array.isArray(this.userMobile)){
        const findItem = lodash.find(this.userMobile,(item)=> item?.uid === uid && currentTime < item?.expired);
        this.clearExpiredUserMoble();
        return findItem?.mobile || '';
      } else {
        const mobileList = getUserMobileList();
        this.setUserMobileData({ userMobile: mobileList });
        this.clearExpiredUserMoble();
        const findItem = lodash.find(mobileList ,(item)=> item?.uid === uid && currentTime < item?.expired);

        return findItem?.mobile || '';
      }
    }
  }
})


export default useCommonStore;